<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use think\Db;

/**
 * 示例接口
 */
class Readingparty extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['MyReadingParty', 'ReadingPartyList', 'joinReadingParty'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];
  	protected $key = 0;
  	protected $value = [];

    /**
     * 无需登录的接口
     * 
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }
  	//木耳读书会
  	public function ReadingPartyList(){
      	$sql = 'select r.* from xmr_reading_party r left join xmr_myreading_party m on r.id=m.rpid where m.id is null && unix_timestamp(now()) < r.start_time';
    	//$ReadingParty = Db::table('xmr_reading_party')->select();
      	$ReadingParty = Db::query($sql);
      	foreach($ReadingParty as $k=>&$v){
        	$v['start_time'] = date('Y-m-d H:i', $v['start_time']);
          	$v['end_time'] = date('Y-m-d H:i', $v['end_time']);
          	$v['cover'] = 'http://'.$_SERVER['SERVER_NAME'].$v['cover'];
        }
      	return $ReadingParty;
    }
  
	//报名参加读书会
  	public function joinReadingParty($rel_name, $rel_tel, $rpid){
    	$uid = Request::instance()->header()['uid'];
      	$res = Db::table('xmr_myreading_party')->where('uid', $uid)->where('rpid', $rpid)->find();
      	if($res){
        	return ['code'=>2, 'msg'=>'你已经报过名了'];
        }
      	$partytime = Db::table('xmr_reading_party')->field('start_time')->where('id', $rpid)->find()['start_time'];
      	if(time() > $partytime){
        	return ['code'=>3, 'msg'=>'已经过了报名时间了'];
        }
      	$partyData = ['uid'=>$uid, 'rpid'=>$rpid, 'rel_name'=>$rel_name, 'rel_tel'=>$rel_tel];
      	Db::table('xmr_myreading_party')->insert($partyData);
      	$mrpid = Db::name('xmr_myreading_party')->getLastInsID();
      	if($mrpid){
        	return ['code'=>1, 'msg'=>'成功'];
        }else{
        	return ['code'=>0, 'msg'=>'失败'];
        }
    }
  	public function datetime($list, $time){
          foreach($list as $k=>&$v ){
              $v[$time[$this->key]] = date('Y-m-d H:i', $v[$time[$this->key]]);
          }
          unset($time[$this->key]);
          $this->key += 1;
      	 if($this->key < count($time)){
          $this->datetime($list, $time);
         }else{
           	$this->value = $list;
         }
    }

}
